package com.niji.littly_donkey_android.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.makeramen.roundedimageview.RoundedImageView;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.activity.*;
import com.niji.littly_donkey_android.bean.Notice;
import com.niji.littly_donkey_android.bean.Order;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.*;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderAdapter extends ArrayAdapter<Order> {
    private static final String TAG = "OrderAdapter";

    private static Context context;
    
    private Activity activity;

    private View mView;

    private static ArrayList<Order> posionList;

    public OrderAdapter(Context context, ArrayList<Order> members)
    {
        super(context,0, members);
        this.context = context;
        this.activity = (Activity) context;
        this.posionList = members;

    }



    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Order order = getItem(position);
        mView = LayoutInflater.from(getContext()).inflate(R.layout.my_order_all_activity, parent, false);
        if(convertView == null)
        {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_order, parent, false);
        }
        TextView order_id = convertView.findViewById(R.id.order_id);
        TextView attractions_id = convertView.findViewById(R.id.attractions_id);
        TextView statusName = convertView.findViewById(R.id.order_status_name);
        TextView price = convertView.findViewById(R.id.order_price);
        TextView ticketsNumber = convertView.findViewById(R.id.order_tickets_number);
        TextView attractsName = convertView.findViewById(R.id.order_attractionsName);
        TextView subscribeTime = convertView.findViewById(R.id.order_subscribe_time);
        TextView priceSum = convertView.findViewById(R.id.order_price_sum);
        RoundedImageView photo = convertView.findViewById(R.id.order_photo);
        Button button1 = convertView.findViewById(R.id.order_btn1);
        Button button2 = convertView.findViewById(R.id.order_btn2);

        if(order.getPhoto() != null){
            if (!order.getPhoto().equals("")){
                NetworkGlideImageLoader.getInstance().displayImage((Activity) context,UrlUtil.URL + order.getPhoto(),photo,0,0);
            }
        }
        statusName.setText(order.getStatusName());
        Integer status = order.getStatus();
        attractions_id.setText("" + order.getAttractionsId());
        order_id.setText("" + order.getId());
        if(status == 1){
            statusName.setTextColor(Color.parseColor("#ff5252"));
            button1.setText("付款");
            button1.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_red));
            button2.setText("取消订单");
            button2.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_grey));
        }else if(status == 2){
            statusName.setTextColor(Color.parseColor("#4258d0"));
            button1.setText("查看订单");
            button1.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_blue));
            button2.setText("退款");
            button2.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_yellow));
        }else if(status == 3){
            statusName.setTextColor(Color.parseColor("#ff5252"));
            button1.setText("再次购买");
            button1.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_red));
            button2.setText("评价");
            button2.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_yellow));
        }else if(status == 4){
            statusName.setTextColor(Color.parseColor("#999999"));
            button1.setText("再次购买");
            button1.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_red));
            button2.setText("删除订单");
            button2.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_grey));
        }else if(status == 5){
            statusName.setTextColor(Color.parseColor("#999999"));
            button1.setText("再次购买");
            button1.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_red));
            button2.setText("删除订单");
            button2.setBackground(convertView.getResources().getDrawable(R.drawable.my_order_grey));
        }
        attractsName.setText(order.getAttractionsName());
        price.setText("￥" + order.getPrice());
        ticketsNumber.setText(order.getTicketsNumber() + "张");
        priceSum.setText("总计： ￥" + (Integer.parseInt(order.getPrice() )* order.getTicketsNumber()));
        subscribeTime.setText("使用时间(当地时间):" + order.getSubscribeTime());

        Button order_btn1 = convertView.findViewById(R.id.order_btn1);
        Button order_btn2 = convertView.findViewById(R.id.order_btn2);
        order_btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String btnName2 = order_btn2.getText().toString().trim();
                if(btnName2.equals("取消订单")){
                    //取消订单
                     Integer id = Integer.parseInt(order_id.getText().toString().trim());
                    String url = UrlUtil.URL + "/order/cancel";
                    RequestQueue requestQueue= Volley.newRequestQueue(context);
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            try {
                                Map<String, Object> map = JsonUtil.jsonToMap(s);
                                Integer code = (Integer) map.get("code");
                                if (code == 0) {
                                    String  data = (String) map.get("data");
                                    Log.i(TAG,data.toString());
                                    Toast.makeText(context, data, Toast.LENGTH_LONG).show();
                                    posionList.remove(position);
                                    notifyDataSetChanged();

                                } else if(code == -1){
                                    Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                                    intent.putExtra("loginCode","-1");
                                    activity.startActivity(intent);
                                    activity.finish();
                                }else {
                                    String  data = (String) map.get("message");
                                    Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
                                    activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                    activity.finish();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e(TAG, volleyError.getMessage(), volleyError);
                        }
                    }) {

                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("order_id",String.valueOf(id));
                            return map;
                        }

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            String sesseionid = new ConnectViaSession(context).GetSession();
                            if (!sesseionid.equals("")) {
                                HashMap<String, String> headers = new HashMap<String, String>();
                                headers.put("cookie", sesseionid);
                                return headers;
                            } else {
                                return super.getHeaders();
                            }
                        }
                    };
                    requestQueue.add(stringRequest);

                }else if(btnName2.equals("退款")){
                    Integer id = Integer.parseInt(order_id.getText().toString().trim());
                    String url = UrlUtil.URL + "/order/edit";
                    RequestQueue requestQueue= Volley.newRequestQueue(context);
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            try {
                                Map<String, Object> map = JsonUtil.jsonToMap(s);
                                Integer code = (Integer) map.get("code");
                                if (code == 0) {
                                    String  data = (String) map.get("data");
                                    Log.i(TAG,data.toString());
                                    Toast.makeText(context, data, Toast.LENGTH_LONG).show();
                                    posionList.remove(position);
                                    notifyDataSetChanged();
                                } else if(code == -1){
                                    Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                                    intent.putExtra("loginCode","-1");
                                    activity.startActivity(intent);
                                    activity.finish();
                                }else {
                                    String  data = (String) map.get("message");
                                    Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
                                    activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                    activity.finish();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e(TAG, volleyError.getMessage(), volleyError);
                            if(volleyError instanceof TimeoutError){
                                Toast.makeText(context,"网络请求超时，请重试！",Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if(volleyError instanceof ServerError) {
                                Toast.makeText(context,"服务器异常",Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if(volleyError instanceof NetworkError) {
                                Toast.makeText(context,"请检查网络",Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if(volleyError instanceof ParseError) {
                                Toast.makeText(context,"数据格式错误",Toast.LENGTH_SHORT).show();
                                return;
                            }

                            Toast.makeText(context,volleyError.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    }) {

                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("order_id",String.valueOf(id));
                            map.put("type",String.valueOf(2));
                            map.put("number",String.valueOf(1));
                            return map;
                        }

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            String sesseionid = new ConnectViaSession(context).GetSession();
                            if (!sesseionid.equals("")) {
                                HashMap<String, String> headers = new HashMap<String, String>();
                                headers.put("cookie", sesseionid);
                                return headers;
                            } else {
                                return super.getHeaders();
                            }
                        }
                    };
                    requestQueue.add(stringRequest);
                }else if(btnName2.equals("评价")){
                    Intent intent = new Intent(context, OrderCommentActivity.class);
                    intent.putExtra("attractions_id",attractions_id.getText().toString().trim());
                    activity.startActivity(intent);
                }else if(btnName2.equals("删除订单")){
                    Integer id = Integer.parseInt(order_id.getText().toString().trim());
                    String url = UrlUtil.URL + "/order/delete";
                    RequestQueue requestQueue= Volley.newRequestQueue(context);
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            try {
                                Map<String, Object> map = JsonUtil.jsonToMap(s);
                                Integer code = (Integer) map.get("code");
                                if (code == 0) {
                                    String  data = (String) map.get("data");
                                    Log.i(TAG,data.toString());
                                    Toast.makeText(context, data, Toast.LENGTH_LONG).show();
                                    posionList.remove(position);
                                    notifyDataSetChanged();
                                } else if(code == -1){
                                    Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                                    intent.putExtra("loginCode","-1");
                                    activity.startActivity(intent);
                                    activity.finish();
                                }else {
                                    String  data = (String) map.get("message");
                                    Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
                                    activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                    activity.finish();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e(TAG, volleyError.getMessage(), volleyError);
                        }
                    }) {

                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("order_id",String.valueOf(id));
                            return map;
                        }

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            String sesseionid = new ConnectViaSession(context).GetSession();
                            if (!sesseionid.equals("")) {
                                HashMap<String, String> headers = new HashMap<String, String>();
                                headers.put("cookie", sesseionid);
                                return headers;
                            } else {
                                return super.getHeaders();
                            }
                        }
                    };
                    requestQueue.add(stringRequest);
                }
            }
        });

        order_btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String btnName1 = order_btn1.getText().toString().trim();
                if(btnName1.equals("付款")){
                    Toast.makeText(context,"暂时缺少付款接口，待实现",Toast.LENGTH_SHORT).show();
                }else if(btnName1.equals("查看订单")){
                    Intent intent = new Intent(context, OrderDetailsActivity.class);
                    intent.putExtra("order_id",order_id.getText().toString().trim());
                    activity.startActivity(intent);
                }else if(btnName1.equals("再次购买")){
                    Intent intent = new Intent(context, ScreenDetailsActivity.class);
                    intent.putExtra("attractions_id",attractions_id.getText().toString().trim());
                    activity.startActivity(intent);
                }
            }
        });

        return convertView;
    }

    /**
     * 删除订单
     * @param id
     */
    private void deleteOrder(int id) {

        String url = UrlUtil.URL + "/order/delete";
        RequestQueue requestQueue= Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        String  data = (String) map.get("data");
                        Log.i(TAG,data.toString());
                        Toast.makeText(context, data, Toast.LENGTH_LONG).show();
                        notifyDataSetChanged();
                    } else if(code == -1){
                        Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        activity.startActivity(intent);
                        activity.finish();
                    }else {
                        String  data = (String) map.get("message");
                        Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
                        activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        activity.finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("order_id",String.valueOf(id));
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(context).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(stringRequest);
    }

    /**
     * 取消订单
     * @param id
     */
    private void cancelOrder(int id) {

    }


    /**
     * 退款
     */
    private void refund(int id) {


    }


}
